const http = require("http")
const qs = require("querystring")

var arr = [
    {
        "name":"小明",
        "score": 90
    }
]

// 再写一个接口 添加学生数据接口。
// https://www.runoob.com/nodejs/node-js-get-post.html

const server = http.createServer((req, res)=> {
    // 这是cors ，允许前端进行跨域。
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.setHeader("X-Powered-By",' 3.2.1')


    res.setHeader("Content-Type", "application/json;charset=utf-8")
    console.log(req.url, req.method)
    // get请求的监听
    if(req.url === "/api/getStudent" && req.method === "GET") {
        res.end(JSON.stringify(arr))
    }else if(req.url === "/api/addStudent" && req.method === "POST") {
        // console.log("这是一个post请求")
        // 2. 开始接收数据(请求体里面)
        var post = "";
        req.on("data", (chunk)=> {
            post += chunk
        })

        req.on("end", ()=> {
            // 这是通过qs.parse 解析数据成对象形式
            var obj = qs.parse(post)
            arr.push({
                name: obj.name,
                score: obj.score
            })

            res.end("添加成功")
        })
    }


    // http://127.0.0.1:5000/api/addStudent  post  {name:"", score: 100}
})

server.listen(5000, ()=> {
    console.log("服务器创建成功")
})